package com.data.controller;

import com.alibaba.fastjson.JSONObject;
import com.csvreader.CsvReader;
import com.data.util.MinioUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Str
 * @Date 2022/2/4 22:34
 * @Description :
 */
@RestController
public class MinioController {

    @Autowired
    private MinioUtils minioUtils;

    @RequestMapping("init")
    public String init() {
        return "file";
    }

    /**
     * 上传
     *
     * @param code      股票代码
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return localhost:8090/upload?code=0600000&startTime=20200101&endTime=20200110
     */
    public String upload(String code, String startTime, String endTime) {
        JSONObject res = new JSONObject();
        //  fields字段表示要抓取的数据类型。
        String urlPath = "http://quotes.money.163.com/service/chddata.html?code=" + code + "&start=" + startTime + "&end=" + endTime + "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP";

        System.out.println("urlPath：" + urlPath);
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类，抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            //设置超时
            httpURLConnection.setConnectTimeout(1000 * 5);
            //设置请求方式，默认是GET
//            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL引用的资源的通信链接（如果尚未建立这样的连接）。
            httpURLConnection.connect();
            // 文件大小
//            int fileLength = httpURLConnection.getContentLength();

            // 控制台打印文件大小
//            System.out.println("您要下载的文件大小为:" + fileLength / 1024 + "KB");

            // 建立链接从请求中获取数据
//            URLConnection con = url.openConnection();
            InputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());
            System.out.println("================");
            minioUtils.putObject("stock", "test3.csv", bin);
            res.put("code", 1);
            res.put("msg", "上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            res.put("code", 0);
            res.put("msg", "上传失败");
        }
        return res.toJSONString();
    }

    /**
     * 获取某个桶的文件列表
     *
     * @return java.util.List
     */
    @RequestMapping("/stockDataList")
    public List StockDataList() {
        return minioUtils.getNameList("stock");
    }

    /**
     * 获取文件的URL
     *
     * @return java.lang.String
     */
    @RequestMapping("/stockDataURL")
    public String StockDataURL() {
        return minioUtils.getObjectURL("stock", "test4.csv");
    }

    /**
     * 读取一个文件的内容
     *
     * @return java.lang.String
     */
    @RequestMapping("/stockData")
    public List StockData() {
        List<String[]> csvList = new ArrayList<String[]>();
        // 获取输入流
        InputStream stock = minioUtils.getObject("stock", "test4.csv");
        try {
            CsvReader reader = new CsvReader(stock, ',', Charset.forName("GBK"));
            while (reader.readRecord()) {
                csvList.add(reader.getValues()); //按行读取，并把每一行的数据添加到list集合
            }
            reader.close();
            System.out.println("读取的行数：" + csvList.size());

            for (int row = 0; row < csvList.size(); row++) {
                System.out.println("-----------------");
                //打印每一行的数据
                System.out.print(csvList.get(row)[0] + ",");
                System.out.print(csvList.get(row)[1] + ",");
                System.out.print(csvList.get(row)[2] + ",");
                System.out.println(csvList.get(row)[3] + ",");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return csvList;
    }
}